package com.groupbuying.orderconsumer.mq;

import com.aliyun.openservices.ons.api.Action;
import com.aliyun.openservices.ons.api.ConsumeContext;
import com.aliyun.openservices.ons.api.Message;
import com.aliyun.openservices.ons.api.MessageListener;
import com.groupbuying.orderconsumer.constant.CommodityOrderMainEnumConstants;
import com.groupbuying.orderconsumer.constant.CommonConstants;
import com.groupbuying.orderconsumer.constant.OrderUshopEnumConstants;
import com.groupbuying.orderconsumer.service.CommodityOrderUshopService;
import com.groupbuying.orderconsumer.service.OrderUshopService;
import com.groupbuying.orderconsumer.utils.JSONUtils;
import com.groupbuying.orderconsumer.utils.apiresult.ApiResult;
import com.groupbuying.orderconsumer.utils.apiresult.ApiResultCode;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.util.Map;

/**
 * 订单消费者监听
 *
 * @Author Vincentxin
 * @Date 2019-05-10
 */
@Component
public class OrderMsgListener implements MessageListener {
    public static final Logger LOGGER = LoggerFactory.getLogger(OrderMsgListener.class);
    @Autowired
    private OrderUshopService orderUshopService;
    @Autowired
    private CommodityOrderUshopService commodityOrderUshopService;

    @Override
    public Action consume(Message message, ConsumeContext context) {
        //验证Topic及Tag
        if (!message.getTopic().equals(OrderMQConfig.TOPIC) || StringUtils.isEmpty(message.getTag())) {
            LOGGER.info("消费了不匹配Topic或者Tag");
            return Action.CommitMessage;

        }
        //获取消息重试次数
        int reconsume = message.getReconsumeTimes();
        if (reconsume == 3) {
            // 消息已经重试了3次，告诉服务器稍后在尝试消费
            LOGGER.info("消费三次不成功，直接以成功处理");
            return Action.CommitMessage;
        }

        //解析消息体
        Map result = JSONUtils.jsonToMap(new String(message.getBody()));
        /**
         * 商品订单定时关闭和支付修改状态用到了id
         */
        //获取订单号
        Object orderId = result.get("orderId")==null?result.get("id"):result.get("orderId");
//        Object orderId = result.get("orderId");
        if (orderId == null){   //防止订单为空，程序没提示
            LOGGER.error("订单消费者监听，订单orderId为空");
            return Action.CommitMessage;
        }
        //获取与Tag匹配的状态值
        String state = matchState(message.getTag());

        LOGGER.info("订单消费者监听,当前tag为:{}",message.getTag());
        // 通过Tag前缀判断--修改交易状态
        if (message.getTag().startsWith(OrderMQConfig.DEAL_TAG_PREFIX)) {
            ApiResult res;

            //如果是定时关闭订单
            if (message.getTag().equals(OrderMQConfig.DEAL_TAG_TIMINGCLOSE)) {
                res = orderUshopService.closeDealState(orderId.toString(), CommonConstants.AUTO_OPERATION);
                LOGGER.info("定时关闭------订单ID：{}，修改情况：{}",orderId,("0".equals(res.getCode())? "失败":"成功"));
            } else {
                res = orderUshopService.updateDealState(orderId.toString(), state);
                LOGGER.info("异步修改订单交易状态------订单ID：{}，修改情况：{}",orderId ,state);
            }


            if (res.getCode().equals(ApiResultCode.SUCCESS.code())) {
                LOGGER.info("交易状态修改成功-------订单Id：{},修改成功:{}",
                        orderId,state==null?CommonConstants.AUTO_OPERATION:state);
                return Action.CommitMessage;
            }
            LOGGER.error("交易状态修改失败! tag:{},orderId:{},失败原因:{} " ,message.getTag(),orderId , res.getMsg());
            //通过Tag前缀判断—-修改订单状态
        } else if (message.getTag().startsWith(OrderMQConfig.ORDER_TAG_PREFIX)) {
            ApiResult res = orderUshopService.updateOrderState(orderId.toString(), state);
            if (res.getCode().equals(ApiResultCode.SUCCESS.code())) {
                LOGGER.info("订单状态修改------订单Id：{}，修改成功状态:{} ",orderId,state);
                return Action.CommitMessage;
            }else if (ApiResultCode.METHOD_ON_THE_WAY.code().equals(res.getCode())){
                LOGGER.error("订单ID:{}正在执行中 tagID：{}",orderId,message.getMsgID());
            }
            LOGGER.error("修改订单状态失败 tag:{},orderId:{},失败原因:{} " , message.getTag() , orderId , res.getMsg());
        } else if (message.getTag().startsWith(OrderMQConfig.COMMODITY_TAG_PREFIX)) {
            ApiResult res = null;
            if (message.getTag().equals(OrderMQConfig.COMMODITY_TAG_TIMINGCLOSE)){//商品关闭订单
                //修改状态：关闭
                result.put("orderState",CommodityOrderMainEnumConstants.ENUM_ORDERSTATE_CLOSED);

                res = commodityOrderUshopService.changeCommodityMainOrderStateService(result);
                LOGGER.info("商品订单关闭------订单Id：{}，修改成功状态:{} ",orderId,state);
            } else if (message.getTag().equals(OrderMQConfig.COMMODITY_TAG_PAY)){//商品更改状态
                //修改状态：待发货
                result.put("orderState", CommodityOrderMainEnumConstants.ENUM_ORDERSTATE_WAIT_FOR_DELIVERY);

                res = commodityOrderUshopService.changeCommodityMainOrderStateService(result);
                LOGGER.info("商品订单状态修改------订单Id：{}",orderId,state);
            }else {
                LOGGER.error("商品订单消费者没有找到对应的tag");
            }

            if (res.getCode().equals(ApiResultCode.SUCCESS.code())) {
                LOGGER.info("订单状态修改------订单Id：{}，修改成功状态:{} ",orderId,state);
                return Action.CommitMessage;
            }
            LOGGER.error("修改商品订单修改状态失败 tag:{},orderId:{},失败原因:{} " , message.getTag() , orderId , res.getMsg());
        }

        return Action.CommitMessage;
    }

    /**
     * 匹配tag和状态枚举类型
     *
     * @param msgTag
     * @return
     */
    private String matchState(String msgTag) {
        switch (msgTag) {
            case OrderMQConfig.DEAL_TAG_CLOSE:
                return OrderUshopEnumConstants.ENUM_DEALSTATE_CLOSED;
            case OrderMQConfig.DEAL_TAG_FREEZE:
                return OrderUshopEnumConstants.ENUM_DEALSTATE_FREEZE;
            case OrderMQConfig.ORDER_TAG_PAY:
                return OrderUshopEnumConstants.ENUM_ORDERSTATE_PAY;
            case OrderMQConfig.ORDER_TAG_REFUNDING:
                return OrderUshopEnumConstants.ENUM_ORDERSTATE_REFUNDING;
            case OrderMQConfig.ORDER_TAG_REFUNDED:
                return OrderUshopEnumConstants.ENUM_ORDERSTATE_REFUNDED;
            case OrderMQConfig.ORDER_TAG_REFUNDFAIL:
                return OrderUshopEnumConstants.ENUM_ORDERSTATE_REFUNDFAIL;
            default:
                return null;
        }
    }
}
